package model

import (
	"time"
	"tools-api/src/common/db/database"
)

// UserLoginRecord 用户登录日志
type UserLoginRecord struct {
	Id           int64     `json:"-"`
	Uuid         string    `json:"-"`
	DeviceType   string    `json:"-"` // 1:Android 2:iOS 9:未知
	DeviceId     string    `json:"-"` // 设备id
	TokenVersion int       `json:"-"` // token登录版本号 小于该版本号的token都失效
	Ip           string    `json:"-"` // ip
	CreatedAt    time.Time `xorm:"created" json:"-"`
	ModifiedAt   time.Time `xorm:"updated" json:"-"`
	DeleteMark   int       `xorm:"delete_mark" json:"-"`
}

func getRecord(uuid, deviceType, deviceId string, record *UserLoginRecord) {
	_, _ = database.JCJEngine.Where("uuid=? and device_type=? and device_id=?", uuid, deviceType, deviceId).Get(record)
}

func (record UserLoginRecord) Create(uuid, deviceType, deviceId, ip string) (int, error) {
	getRecord(uuid, deviceType, deviceId, &record)
	record.Ip = ip
	var err error
	if record.Id > 0 {
		record.TokenVersion = record.TokenVersion + 1 // 版本加1
		_, err = database.JCJEngine.ID(record.Id).Cols("ip", "token_version").Update(&record)
	} else {
		record.Uuid = uuid
		record.DeviceType = deviceType
		record.DeviceId = deviceId
		record.TokenVersion = 1
		_, err = database.JCJEngine.InsertOne(&record)
	}
	return record.TokenVersion, err
}

func (record UserLoginRecord) GetTokenVersion(uuid, deviceType, deviceId string) int {
	getRecord(uuid, deviceType, deviceId, &record)
	return record.TokenVersion
}

// IncreaseTokenVersion 退出登录的时候
func (record UserLoginRecord) IncreaseTokenVersion(uuid, deviceType, deviceId string) error {
	getRecord(uuid, deviceType, deviceId, &record)
	if record.Id > 0 {
		record.TokenVersion = record.TokenVersion + 1 // 版本加1
		_, err := database.JCJEngine.ID(record.Id).Cols("token_version").Update(&record)
		return err
	}
	return nil
}

func (record UserLoginRecord) Verify(uuid, deviceType, deviceId string, tokenVersion int) bool {
	getRecord(uuid, deviceType, deviceId, &record)
	if record.Id <= 0 {
		return false
	}
	return tokenVersion == record.TokenVersion
}
